<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      var exist = function (board, word) {
        let res = false
        function dfs(i, j, start) {
          if (
            i < 0 ||
            i >= board.length ||
            j < 0 ||
            j >= board[0].length ||
            board[i][j] == 0 ||
            board[i][j] != word[start]
          ) {
            return false
          }
          if (start == word.length - 1) return true
          let temp = board[i][j]
          board[i][j] = 0
          let flag =
            dfs(i - 1, j, start + 1) || dfs(i + 1, j, start + 1) || dfs(i, j - 1, start + 1) || dfs(i, j + 1, start + 1)
          board[i][j] = temp
          return flag
        }
        for (let i = 0; i < board.length; i++) {
          for (let j = 0; j < board[0].length; j++) {
            if (board[i][j] == word[0]) {
              res = dfs(i, j, 0)
              if (res) return res
            }
          }
        }
        return false
      }
    </script>
  </body>
</html>
